package com.xin.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.aliyuncs.exceptions.ClientException;
import com.xin.constant.MessageConstant;
import com.xin.constant.RedisMessageConstant;
import com.xin.entity.Result;
import com.xin.pojo.Order;
import com.xin.service.OrderService;
import com.xin.utils.SMSUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @Author 夜天
 * @Date 2021/12/24 19:57
 * @Version 1.0.0
 * @description： 体检预约
 */
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;
    // 在线体检预约
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map){
        String telephone = (String) map.get("telephone");
        // 从Redis中获取保存的验证码
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        String validateCode = String.valueOf(map.get("validateCode"));
        // 将用户输入验证码和Redis保存的验证码作比较
        if(validateCode != null && validateCodeInRedis != null && validateCode.equals(validateCodeInRedis)){
            // 比对成功
            Result order = null;
            try {
                // 设置预约类型，微信预约，电话预约
                map.put("orderType", Order.ORDERTYPE_WEIXIN);
                // Dubbo调用服务完成预约服务处理
                order = orderService.order(map);
            } catch (Exception e) {
                e.printStackTrace();
            }

            if(order.isFlag()){
                try {
                    // 预约成功，为用户发送消息
                    SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE,telephone,(String) map.get("orderDate"));
                } catch (ClientException e) {
                    e.printStackTrace();
                }
            }
            return order;
        }else {
            // 失败，返回结果给页面,验证码发送失败
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }

    }
    // 根据预约 Id 查询预约相关信息
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
            Map map = orderService.findById(id);
            // 查询预约信息成功
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            // 查询预约信息失败
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
